import { compareValue, hashValue } from '@/lib/bcrypt';
import { fortyFiveMinutesFromNow } from '@/lib/date-time';
import { db } from '@/lib/db';
import { AppError } from '@/server/appError';
import { ErrorCode } from '@/server/common/error-code.enum';
import { getUserByEmail } from '@/server/controllers/userController';

export const register = async ({ user_email, user_name, user_password }) => {
    const hashedPassword = await hashValue(user_password);
    const existingUser = await getUserByEmail(user_email);
    if (existingUser) throw new AppError(ErrorCode.AUTH_EMAIL_ALREADY_EXISTS);
    const newUser = await db.tb_user.create({
        data: {
            user_name,
            user_email,
            user_password: hashedPassword
        }
    });
    // TODO: Verification code
    const verificationCode = {
        userId: newUser.user_id,
        expiresAt: fortyFiveMinutesFromNow()
    };
    // TODO: Send verification token email
    return newUser;
};

export const login = async ({ user_email, user_password }) => {
    const user = await getUserByEmail(user_email);
    if (!user) throw new AppError(ErrorCode.AUTH_USER_NOT_FOUND);
    const passwordMatched = await compareValue(user_password, user.user_password);
    if (!passwordMatched) throw new AppError(ErrorCode.AUTH_INVALID_CREDENTIAL);
};
